<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class registerController extends Controller
{
    //注册页面
    public function index()
    {
        return view('register/index');
    }

    /**
     * 注册功能
     * @todo 1: 验证失败跳转到对应的页面的时候丢失了用户填充的原始信息， 2：成功后应该是跳转到用户的前一个页面，而不是登录页面
     * @author qinjunkun@globalegrow.com
     * @date 2017/7/23
     * @return \Illuminate\Http\RedirectResponse
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'     => 'required|unique:users,name',
            'email'    => 'required|unique:users,email',
            'password' => 'required|min:8|max:20|confirmed',
        ], [
            'name.unique'        => '用户名已经存在',
            'email.unique'       => '邮箱已经存在',
            'password.confirmed' => '两次输入的密码不匹配',
        ]);

//
//        $this->validate(\request(), [
//            'name'     => 'required|unique:users,name',
//            'email'    => 'required|unique:users,email',
//            'password' => 'required|min:8|max:20|confirmed',
//        ], [
//            'name.unique'        => '用户名已经存在',
//            'email.unique'       => '邮箱已经存在',
//            'password.confirmed' => '两次输入的密码不匹配',
//        ]);

        if ($validator->fails()) {
            return redirect('/register')
                ->withErrors($validator)
                ->withInput();
        }

        $name = \request('name');
        $email = \request('email');
        $password = bcrypt(\request('password'));

        User::create(compact('name', 'email', 'password'));

        //严谨来说应该是跳转到来源页面，不是抽屉页面
        return back();
    }


}
